package pikasial.graphique;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import pikasial.images.PikImage;

public class BoiteCommentaire extends JPanel {

	private static final long serialVersionUID = 7815564837675736091L;
	private PikImage image;
	private JTextArea textArea;
	private JButton ok;
	private JButton cancel;
	private boolean readyToClose;

	public BoiteCommentaire(PikImage pik) {
		super();
		image = pik;
		readyToClose = false;
		Box b = Box.createHorizontalBox();
		b.setAlignmentX(Box.CENTER_ALIGNMENT);
		URL okPath = getClass().getResource(pikasial.utils.PikasialConstantes.OK_ICON_PATH);
		URL cancelPath = getClass().getResource(pikasial.utils.PikasialConstantes.CANCEL_ICON_PATH);
		ok = new JButton(new ImageIcon(okPath));
		cancel = new JButton(new ImageIcon(cancelPath));
		ok.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (!textArea.getText().trim().equals("")) {
					image.setCommentaire(textArea.getText());
					close();
				}
			}
		});
		cancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				close();
			}
		});
		b.add(ok);
		b.add(cancel);

		textArea = new JTextArea(new javax.swing.text.PlainDocument() {
			private static final long serialVersionUID = -1800381228731962537L;
			private static final int MAX_LENGTH = 1024;
			public void insertString(int offs, String str, javax.swing.text.AttributeSet a)
				throws javax.swing.text.BadLocationException {
				if (offs+str.length() <= MAX_LENGTH)
		            super.insertString(offs, str, a);
				else
					super.insertString(offs, str.substring(0, MAX_LENGTH-offs),a);
			}
		},"",8,45);
		String initComment = image.getCommentaire();
		if (initComment != null) {
			textArea.setText(initComment);
		}
		textArea.setLineWrap(true);
		textArea.setBorder(BorderFactory.createTitledBorder("Entrez votre commentaire :"));
		add(textArea);
		add(b);
	}

	public synchronized boolean isReadyToClose() { return readyToClose;	}

	public synchronized void close() { readyToClose = true; notifyAll(); }

}
